﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using app.Models;
using AmuTools;
using System.IO;

namespace app.Api
{
    /*
        数据库的初始化，备份等操作

        初始化的目的是保证一些必要的数据添加到数据库中，甚至可以自动建立表（通过执行sql文件代码）等
    */
    public class ApiDatabase : ApiBase
    {
        public ApiDatabase(Controller ctx) : base(ctx) { }

        public string database_root_path
        {
            get
            {
                string temp = ctx.Server.MapPath(@"~/DatabaseManager/");
                if (!Directory.Exists(temp))
                {
                    Directory.CreateDirectory(temp);
                }
                return temp;
            }
        }
        public string storedprocedures_path
        {
            get
            {
                string temp = ctx.Server.MapPath("~/") + "Models/StoredProcedures/";
                if (!Directory.Exists(temp))
                {
                    Directory.CreateDirectory(temp);
                }
                return temp;
            }
        }

        #region 自定义请求参数
        // 作者
        string req_author { get { return GetStringParam(new ReqStringParamOption { Name = "author", Level = REQPARAMLEVEL.FREE, DefaultValue = "未命名" }); } }

        #endregion

        public void Do(string action)
        {
            switch (action)
            {
                case "init":
                    List<string> logs = G.CreateDatabase(ctx, storedprocedures_path);
                    ResponseJson(new ObjectResult { data = logs });
                    break;
                case "backup_database":
                    {
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.BACKUP_DATABASE).BackupDatabase());
                        string databaseName = GetStringParam(new ReqStringParamOption { Name = "databaseName" });
                        if (File.Exists(database_root_path + databaseName))
                        {
                            ThrowStatus(STATUS.HAS_DATABASE, "该数据库备份已存在，请重新生成备份！");
                            return;
                        }
                        else
                        {
                            string path = database_root_path + databaseName;
                            string sql = string.Format("backup database ofsp to disk='{0}' with init", path);
                            G.DB.Set(sql);
                            ResponseJson(new Result());
                            RecordLog(PERMISSIONOPERATION.BACKUPDATABASE, UserName + "备份数据库，备份数据库名称为：" + databaseName);
                        }
                        break;
                    }
                case "get_databases":
                    {
                        List<string> allDatabase = G.DB.GetSqlFiles(database_root_path, new string[] { "*.bak" }).Select(r => r.Key + ".bak").ToList();
                        ResponseJson(new ListResult<string> { list = allDatabase });
                        break;
                    }
                case "delete_database":
                    {
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.DELETE_DATABASE).Delete());
                        string deleteName = GetStringParam(new ReqStringParamOption { Name = "delete_database" });
                        if (File.Exists(database_root_path + deleteName))
                        {
                            File.Delete(database_root_path + deleteName);
                            ResponseJson(new Result());
                            RecordLog(PERMISSIONOPERATION.DELETE, UserName + "删除备份数据库，数据库名称为：" + deleteName);
                        }
                        else
                        {
                            ThrowStatus(STATUS.FAILED_DELETE, "该数据库备份文件已丢失，删除失败！");
                        }
                        break;
                    }
                case "restore_database":
                    {
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.RESTORE_DATABASE).RestoreDatabase());
                        string restore_name = GetStringParam(new ReqStringParamOption { Name = "restore_databaseName" });
                        if (File.Exists(database_root_path + restore_name))
                        {
                            string path = database_root_path + restore_name;
                            string sql = string.Format("Alter database {0} Set Offline With rollback immediate; ", "ofsp");
                            sql += string.Format("restore database {0} from disk='{1}' With Replace;", "ofsp", path);
                            sql += string.Format("Alter database {0} Set Online With Rollback immediate;", "ofsp");
                            G.DB.Set(sql);
                            ResponseJson(new Result());
                            RecordLog(PERMISSIONOPERATION.RESTOREDATABASE, UserName + "还原数据库，数据库名称为：" + restore_name);
                        }
                        else
                        {
                            ThrowStatus(STATUS.HAS_DATABASE, "该数据库备份文件已丢失，还原失败！");
                        }
                        break;
                    }
                default: break;
            }
        }
    }


}